package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import io.swagger.annotations.Api;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 新增菜品
 */
@Api(tags = "菜品分类")
@RestController
@RequestMapping("/dish")
@SuppressWarnings("all")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithDishFlavor(dishDto);
        redisTemplate.delete("dish_"+dishDto.getCategoryId());
        return R.success("新增菜品成功");

    }

    /**
     * 分页查询菜品
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<DishDto>> page(Integer page,Integer pageSize,@RequestParam(required = false) String name) {
        //构造分页条件
        Page<Dish> pageInfo1=new Page<>(page,pageSize);
        //构造条件对象
        QueryWrapper<Dish> queryWrapper=new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(name),"name",name);
        queryWrapper.orderByAsc("sort").orderByDesc("update_time");
        dishService.page(pageInfo1,queryWrapper);


        //对Page<Dish> PageInfo 做数据处理
        Page<DishDto> pageInfo2=new Page<>(page,pageSize);

        BeanUtils.copyProperties(pageInfo1,pageInfo2,"records");
        //将page1中的list<Dish>转为 list<DishDto>
        List<DishDto> dishDtoList=new ArrayList<>();
        //遍历page1中的list集合
        for (Dish dish : pageInfo1.getRecords()) {
            //将Dish转变为DishDto
            DishDto dishDto=new DishDto();
            BeanUtils.copyProperties(dish,dishDto);
            //处理分类名称
            Category category = categoryService.getById(dishDto.getCategoryId());
            dishDto.setCategoryName(category.getName());
            dishDtoList.add(dishDto);
        }
        pageInfo2.setRecords(dishDtoList);
        return  R.success(pageInfo2);

    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */

    @GetMapping("/{id}")
    public R<DishDto> findById(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 更新菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateByIdWithFlavor(dishDto);
        //清理所有菜品的缓存数据(删除所有，不用)
        Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        redisTemplate.delete(keys); //删除这些key
        return R.success("修改菜品信息成功");
    }


    /**
     * 根据分类id查询菜品列表
     * @param
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list (@RequestParam Long categoryId){
        // 在list方法中,查询数据库之前,先查询缓存, 缓存中有数据, 直接返回
        String redisKey="dish_"+categoryId;
        List<DishDto> data = (List<DishDto>) redisTemplate.opsForValue().get(redisKey);
        if(data!=null){
            return R.success(data);
        }


        //构造查询条件
        QueryWrapper<Dish> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("category_id",categoryId);
        queryWrapper.eq("status",1);
        queryWrapper.orderByAsc("sort").orderByDesc("update_time");
        List<Dish> dishList = dishService.list(queryWrapper);

        //转换数据将 List<Dish> 转换成 List<DishDto>
        List<DishDto> dishDtoList=new ArrayList<>();
        //遍历 dishlist
        for (Dish dish : dishList) {
            DishDto dishDto1=new DishDto();
            //将dish的数据拷贝到dishdto
            BeanUtils.copyProperties(dish,dishDto1);
            QueryWrapper<DishFlavor>dishFlavorQueryWrapper=new QueryWrapper<>();
            dishFlavorQueryWrapper.eq("dish_id",dish.getId());
            List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorQueryWrapper);
           //设置dishdto的口味集合
            dishDto1.setFlavors(dishFlavorList);
            //将dishdto 添加dishdtolist 集合中
            dishDtoList.add(dishDto1);
        }
        //将数据添加到redis缓存中,设置过期时间
        redisTemplate.opsForValue().set(redisKey,dishDtoList,30, TimeUnit.MINUTES);


        return R.success(dishDtoList);

    }

}

